<html>
  <head>
     <script type="text/javascript" src="scripts/jquery-1.4.2.min.js"></script>
     <script type="text/javascript" src="scripts/showdown.js"></script>
	 <script type="text/javascript" src="scripts/wikid.js"></script>
	 <script type="text/javascript" src="scripts/jsonedit.js"></script>
	 <script type="text/javascript" src="scripts/json.js"></script>
	 <script src="/_utils/script/couch.js?0.11.0"></script> 
	 <script src="/_utils/script/futon.format.js?0.11.0"></script> 
	 <script src="/_utils/script/jquery.couch.js?0.11.0"></script> 
	 <link rel="stylesheet" type="text/css" href="scripts/jsonwidget.css" />
	 <script type="text/javascript">
	 
	 
	 
	$(function() {
		var je;
		db_name = dbname();
		db = new CouchDB(db_name, {"X-Couch-Full-Commit":"true"});
		db.info();
		wikid_id = wikiId();
		anchor_val = anchor();
		doc = null;
		//console.log('anchor ' + anchor_val);
		if (anchor_val == '#newInstance') {
			//console.log('swap ' + anchor_val);
			doc = db.open(wikid_id);
			// the doc will be the tag
			fields = doc['-fields'];
			key = wikid_id + "_" +  guid();
			tags = [];
			tags.push(wikid_id);
			if (fields != undefined && fields.key_strategy && fields.key_strategy == "autoincrement") {
				
			}
			if (fields != undefined && fields.key_strategy && fields.key_strategy == "function") {
				var func = fields.key_strategy_function;
				if (func != null) {
					//$('.jeclass').live("change", function() {
						//je.updateJSON();
						//var obj = JSON.parse($('#je_sourcetextarea').val());
						//console.log('aaaaa');
					//});
				}
			}
			doc = {
					_id : key,
					"-wiki" : "",
					
					"-tags" : tags
				};
			current_tag = wikid_id;
			wikid_id = key;
			showTag(current_tag);
			
		} else if (anchor_val == '#new'){
		    key = 'New Document'
		    tags = [];
			tags.push(wikid_id);
			doc = {
					_id : key,
					"-wiki" : "",
					
					"-tags" : tags
				};
			wikid_id = key;
			$('#doc_id').show().change(function() {
				// check if there is a doc already with that ID
				
				test_doc = db.open($(this).val());
				if (test_doc != null) {
    					$('#doc_id_error').text('A document already exists with this ID').show();
				} else {
					$('#doc_id_error').text('').hide();
				}

			});
		} else {
			doc = db.open(wikid_id);
			if (doc == null) {
				doc = {
					_id : wikid_id,
					"-wiki" : "",
				};
			}			
		}
		jsonwidget.language = 'en';		
		title = wikid_id.replace(/_/g," ");
		$('#title').text(title);
		$('#content').val(doc['-wiki']);
		
		var tags_values = doc['-tags'];
		if (tags_values !== undefined && tags_values != null) {
			jQuery.each(tags_values, function(i, val) {
				$('#taglist').append('<li class="tag">'  + val + '</li>');
			});
		}
		
		var fields = doc['-fields'];
		if (fields === undefined || fields == null) {
			$('#fields_button').show().click(function() {
				$(this).hide();
				$('#fields').show();
			})
			$('#fields').hide();
		} else {
			$('#fields_button').hide();
			$('#fields').show();
			$('#fields').val(JSON.stringify(fields));
			
			$('#schema_editor').show();

			//$('#schema_sourcetextarea').val(JSON.stringify(fields));
			//console.log('stringing out the schema ' );
			//schema_je = new jsonwidget.editor();
			//schema_je.htmlids = {
			//	"warningdiv": "schema_warningdiv",
			//	"formdiv": "schema_formdiv",
			//	"schemaformdiv": "schema_schemaformdiv",
			//	"sourcetextarea": "schema_sourcetextarea",
			//	"schematextarea": "schema_schematextarea",
			//	"schemaschematextarea": "schema_schemaschematextarea",
			//	"byexamplebutton": "schema_byexamplebutton",
			//	"sourcetextform": "schema_sourcetextform"
			//}
			
			
			//schema_je.htmlbuttons = {
			//	form: "schema_formbutton",
			//	source: "schema_sourcebutton",
			//	schemasource: "schema_schemasourcebutton",
			//	schemaform: "schema_schemaformbutton"
			//}
			
			//schema_je.setView('form');		
			
			
		}
		
		
		

		
		
		var current_tag;
		$('.tag').live("click", function() {
			next_tag = $(this).text();
			showTag(next_tag);
		});
		
		function showTag(next_tag) {
			$('#field_editor').show();
			if (je != null) {
				je.updateJSON();
				doc[current_tag] = JSON.parse($('#je_sourcetextarea').val());
				$('#je_sourcetextarea').val(null);
			}
			current_tag = next_tag;
			var tag_value = doc[current_tag];
			if (tag_value === undefined || tag_value == null) {
				$('#je_sourcetextarea').val('');
			} else {
				$('#je_sourcetextarea').val(JSON.stringify(tag_value));
			}
			
			//console.log('click on: ' + tag);
			doc_tag = db.open(current_tag);
			//console.dir(doc_tag['-fields']);
			$('#je_schematextarea').val(JSON.stringify(doc_tag['-fields']));
			je=new jsonwidget.editor();
			je.setView('form');		
		}
		
		
		
		
		jQuery.each(doc, function(i, val) {
			if (i[0] != '-' && i[0] != '_') {
			    var row = $('<tr><td>' + i + '</td><td class="val"></td></tr>');
				row.find(".val").append(_renderValue(val));
				$('#props').append(row);
			}
		});
		
		$('#saveButton').click(function() {
			anchor_val = anchor();
			if (anchor_val == "#new") {
				doc._id = $('#doc_id').val();
				wikid_id = doc._id;
			}
		
			doc['-wiki'] = $('#content').val();
			if (je !== undefined && je != null) {
				je.updateJSON();
				doc[current_tag] = JSON.parse($('#je_sourcetextarea').val());
			}
			var fields_value = $('#fields').val();
			//console.log('fields_value ' + fields_value);
			if (fields_value != null && fields_value != "") {
				//console.log('fields_value 2');
				doc['-fields'] = JSON.parse(fields_value);
				//console.log("updating fields");
				//console.dir(doc['-fields']);
			}
			
			var now = new Date();
			doc["-lastmodified"] = iso8601(now);
			//alert('saving at: ' + now);
			//console.log('saveing');
			//console.dir(doc);
			db.save(doc);
			window.location = "index.html?" + wikid_id;
		});
		$('#cancelButton').click(function() {
			
			anchor_val = anchor();
			if (anchor_val == "#new" || anchor_val == "#newInstance") {
				parent = wikiId();
				window.location = "index.html?" + parent;
			} else {
				window.location = "index.html?" + wikid_id;
			}
		});
		
	});
	 </script>
  </head>
  <body>  
	 
	<h1 id="title"></h1>
	<input type="text" name="doc_id" id="doc_id" style="display: none; width: 500px;" /><br/>
	<div id="doc_id_error">
	
	</div>
	
	
	<textarea rows="10" cols="55" id="content"></textarea>
	
	<input type="button" value="Fields" style="display:none;" id="fields_button"/>
	<textarea rows="10" cols="55" id="fields" style="display:none;"></textarea>





	
	<div class="tags">
		<ul id="taglist">
		</ul>
	</div>

	<div id="field_editor" style="display:none;">
		<div id="je_warningdiv"></div>
		<div>
			<span id="je_formbutton" style="cursor: pointer">[Edit w/Form]</span>
			<span id="je_sourcebutton" style="cursor: pointer">[Edit Source]</span>		
		</div>

		<div id="je_formdiv" style="text-background: white"></div>

		<div>
			<div id="je_schemaformdiv" style="text-background: white"></div>

			<textarea id="je_schematextarea" style="display: none" rows="30" cols="80"></textarea>

			<form method='POST' id="je_sourcetextform">	
				<textarea id="je_sourcetextarea" rows="30" cols="80" name="sourcearea"></textarea>
			</form>
		</div>    
	 </div>
	 <input type="button" value="Save" id="saveButton" />
	 <input type="button" value="Cancel" id="cancelButton" />
  </body>
 </html>